<template>
  <el-dialog :visible.sync="visible" v-if="visible" :title="title">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="车牌" prop="carNo">
        <el-input v-model="formData.carNo" placeholder="请输入车牌"/>
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-input v-model="formData.color" placeholder="请输入颜色"/>
      </el-form-item>
      <el-form-item label="车辆品牌" prop="parentId">
        <el-cascader style="width: 100%" :props="props" v-model="formData.ps" filterable clearable></el-cascader>
      </el-form-item>
      <el-form-item label="车辆类型">
        <el-radio-group v-model="formData.type">
          <el-radio :label="1">轿车</el-radio>
          <el-radio :label="2">SUV</el-radio>
          <el-radio :label="3">商务</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="车辆照片">
        <el-upload :action="uploadUrl" :headers="uploadHeader" :limit="5" :file-list="imageFileList" list-type="picture-card" ref="image" :on-success="imageSuccess" :before-upload="beforeUpload" :on-exceed="onExceed">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}" style="height: 100%;width: 100%">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <div class="el-upload-list__item-actions">
              <span @click="showImage(file)"><i class="el-icon-zoom-in"></i></span>
              <span @click="removeImage(file,'image')"><i class="el-icon-delete"></i></span>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">可用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="imageDialog" title="查看图片" v-if="imageDialog" append-to-body>
      <a :href="imageSrc" target="_blank" title="点击查看原图" style="display: block;height: 100%;width: 100%">
        <img :src="imageSrc" alt="" style="display: block;height: 100%;width: 100%">
      </a>
    </el-dialog>
  </el-dialog>
</template>

<script>
const formData = {
  id: '',
  carNo: '',
  color: '',
  brandId: '',
  status: 1,
  type: 1,
  imageList: '',
  ps: []
}
export default {
  name: 'CarUpdate',
  data () {
    return {
      visible: false,
      title: '添加数据',
      formData,
      rules: {
        carNo: [{
          required: true,
          message: '车牌不能为空'
        }],
        color: [{
          required: true,
          message: '颜色不能为空'
        }]
      },
      baseImage: process.env.VUE_APP_IMAGE_URL,
      uploadUrl: process.env.VUE_APP_URL + 'upload',
      uploadHeader: {
        token: this.$cookies.get('token')
      },
      imageFileList: [],
      imageDialog: false,
      imageSrc: '',
      props: {
        value: 'id',
        label: 'brandName',
        lazy: true,
        lazyLoad: (node, resolve) => {
          const parentId = node.data?.id ?? 0
          this.$http.get('brand/page', { parentId }).then(data => {
            if (data) {
              const rows = data.rows.map(item => {
                return {
                  ...item,
                  leaf: item.child === 0
                }
              })
              resolve(rows)
            }
          })
        }
      }
    }
  },
  methods: {
    init (id) {
      this.visible = true
      this.title = id ? '修改数据' : '添加数据'
      this.formData = { ...formData }
      this.imageFileList.length = 0
      if (id) {
        this.$http.get(`car/info/${id}`).then(data => {
          if (data) {
            let ps = `${data.ps}-${data.brandId}`
            ps = ps.split('-').map(item => parseInt(item))
            this.formData = { ...data, ps }
            this.$http.get('car/images/' + data.id).then(data => {
              if (data.length > 0) {
                this.imageFileList = data.map(item => {
                  return { url: this.baseImage + item.carImage, response: { data: item.carImage }, name: item.carImage }
                })
              }
            })
          }
        })
      }
    },

    onExceed () {
      this.$message.error('超出个数限制！')
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isImage) {
        this.$message.error('请上传图片，格式支持：jpg,jpeg,png,gif')
      }
      const isLt20M = (file.size / 1024 / 1024) < 20
      if (!isLt20M) {
        this.$message.error('图片大小不能超过20MB')
      }
      return isImage && isLt20M
    },
    imageSuccess (res) {
      if (res.code !== 200) {
        this.$message.error(`上传异常:{${res.msg}}`)
      }
    },
    removeImage (file, ref) {
      this.$confirm('确定删除该图片吗?', '询问', { type: 'info' }).then(() => {
        this.formData[ref] = ''
        this.$refs[ref].handleRemove(file)
      }).catch(() => {})
    },
    showImage (file) {
      this.imageDialog = true
      this.imageSrc = file.url
    },
    submit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.formData.ps.length === 0) {
            this.$message.error('请选择品牌！')
            return false
          }
          this.formData.brandId = this.formData.ps[this.formData.ps.length - 1]
          const imageList = this.$refs.image.uploadFiles.map(item => item.response.data)
          this.formData.imageList = imageList.join()
          this.$http.post('car/update', this.formData).then(() => {
            this.$message.success('操作成功')
            this.visible = false
            this.$emit('closeDialog')
          }).catch(() => {})
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
